<!-- 资源信息 -->
<template>
  <div class="table">
    <div class="container">
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <i class="el-icon-search"></i> 查询条件：
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row :gutter="10">
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-select v-model.trim="searchCondition.type"
                     placeholder="资源分类"
                     class="">
            <el-option v-for="item in selectMenuTypeSearch"
                       :label="item.dictLabel"
                       :value="item.dictValue"
                       :key="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.name"
                    placeholder="资源名称"></el-input>
        </el-col>
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.url"
                    placeholder="资源路径"></el-input>
        </el-col>

        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-button type="success"
                     icon="el-icon-search"
                     :disabled="disabledbtn"
                     @click="searchInfo">搜索</el-button>
          <el-button type="warning"
                     icon="el-icon-refresh"
                     :disabled="disabledbtn"
                     @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 查询结果：</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="handle-box">
        <el-button type="primary"
                   icon="el-icon-plus"
                   class="mr10"
                   :disabled="disabledbtn"
                   @click="addData">新增</el-button>
        <el-popconfirm placement="top"
                       width="160"
                       title="你确定要删除吗?"
                       @onConfirm="batchDelete('deleteResourceInfo')">
          <el-button type="danger"
                     icon="el-icon-delete"
                     class="mr10"
                     :disabled="disabledbtn"
                     slot="reference">批量删除</el-button>
        </el-popconfirm>
      </div>
      <el-table :data="tableData"
                border
                class="table"
                ref="multipleTable"
                v-loading="loading"
                :reserve-selection="true"
                @row-dblclick="rowDblclick">
        <el-table-column type="index"
                         align="center"> </el-table-column>
        <el-table-column type="selection"
                         width="55"
                         align="center"></el-table-column>
        <el-table-column prop="type"
                         label="资源分类"
                         align="center">
        </el-table-column>
        <el-table-column prop="name"
                         label="名称"
                         align="center">
        </el-table-column>
        <el-table-column prop="url"
                         label="url地址"
                         align="center">
        </el-table-column>
        <el-table-column prop="method"
                         label="方法"
                         align="center">
        </el-table-column>
        <el-table-column prop="description"
                         label="描述"
                         align="center">
        </el-table-column>
        <el-table-column label="操作"
                         width="180"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-view"
                       @click="handleViewEdit(scope.$index, scope.row, 'view', '查看')">查看
            </el-button>
            <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleViewEdit(scope.$index, scope.row, 'edit', '编辑')">编辑
            </el-button>
            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top"
                             width="160"
                             title="你确定要删除吗?"
                             @confirm="deleteRow('deleteResourceInfo')">
                <el-button type="text"
                           icon="el-icon-delete"
                           class="red"
                           slot="reference"
                           @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       layout="total, sizes, prev, pager, next, jumper"
                       :page-size="searchCondition.size"
                       :current-page="searchCondition.current"
                       :page-sizes="pageSizes"
                       :total="total"
                       :hide-on-single-page="false">
        </el-pagination>
      </div>
    </div>

    <!-- 新增编辑查看弹出框 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="editVisible"
               width="60%"
               :close-on-click-modal="closeOnClickModal"
               @closed="closedFormDialog">
      <el-form ref="resourceForm"
               :model="resourceForm"
               :rules="rules"
               v-loading="loadingDialog"
               label-width="150px">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="资源编码："
                          prop="code">
              <el-input v-model.trim="resourceForm.code"
                        placeholder="属性类型编码">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="资源分类："
                          prop="type">
              <el-select v-model.trim="resourceForm.type"
                         placeholder="资源分类"
                         class="">
                <el-option v-for="item in selectMenuType"
                           :label="item.dictLabel"
                           :value="item.dictValue"
                           :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="资源名称："
                          prop="name">
              <el-input v-model.trim="resourceForm.name"
                        placeholder="资源名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="请求类型："
                          prop="method">
              <el-select v-model.trim="resourceForm.method"
                         placeholder="请求类型"
                         class="">
                <el-option v-for="item in selectrRequestType"
                           :label="item.dictLabel"
                           :value="item.dictValue"
                           :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="20">
            <el-form-item label="资源地址："
                          prop="url">
              <el-input v-model.trim="resourceForm.url"
                        placeholder="资源地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="20">
            <el-form-item label="资源描述："
                          prop="description">
              <el-input v-model.trim="resourceForm.description"
                        type="textarea"
                        autosize
                        placeholder="资源描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelSubmit('resourceForm')">取 消</el-button>
        <el-button type="primary"
                   :disabled="disabledbtn"
                   v-if="!isDisabledbtn"
                   @click="submitForm('resourceForm',resourceForm,methodType,'commonResourceInfo','getResourceInfo')">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ResourceInfo',
  data() {
    return {
      selectrRequestTypeSearch: [],
      selectrRequestType: [],
      selectMenuTypeSearch: [],
      selectMenuType: [],

      tableData: [] /* 表格中所有数据 */,
      selectTableData: [] /* 选中行数据 */,

      dialogTitle: '' /* 新增编辑标题 */,
      editVisible: false /* 新增编辑显示隐藏 */,

      /* 是否可以通过点击 modal 关闭 Dialog	 */
      closeOnClickModal: false,

      delVisibleType: 'delete' /* 删除类型（单选，多选） */,
      disabledbtn: false /* 按钮可用与不可用 */,
      isDisabledbtn: false /* 按钮显示或隐藏 */,

      loading: true,
      loadingDialog: false /* 对话框中数据提交加载 */,
      showType: 'add' /* 用于对话框显示 类型标记 */,
      methodType: 'POST' /* 请求类型 */,

      total: 0 /* 总数 */,
      pageSizes: [10, 20, 30, 40, 50, 100],

      /* 查询条件 */
      searchCondition: {
        name: '',
        url: '',
        method: '',
        type: '',
        current: 1,
        size: 10
      },
      /* 表单数据 */
      resourceForm: {
        id: '',
        code: '',
        name: '',
        url: '',
        type: '',
        description: '',
        method: ''
      },
      /* 校验规则 */
      rules: {
        code: [{ required: true, message: 'code名称必填', trigger: 'blur' }],
        type: [{ required: true, message: '资源分类必选', trigger: 'blur' }],
        name: [{ required: true, message: '资源名称必填', trigger: 'blur' }],
        method: [
          { required: true, message: '资源请求方法必填', trigger: 'blur' }
        ],
        url: [{ required: true, message: 'url地址必填', trigger: 'blur' }],
        description: [
          { required: true, message: '描述信息必填', trigger: 'blur' }
        ]
      },
      /* 删除时所需的编号 删除时的id */
      id: -1
    };
  },
  created() {
    /* 获取表格信息 */
    this.getResourceInfo();
    /* 初始化请求类型，资源类型信息 */
    this.getDictDataInfo('request_type', ['selectrRequestType']);
    this.getDictDataInfo('resource_type', [
      'selectMenuTypeSearch',
      'selectMenuType'
    ]);
  },
  computed: {},
  methods: {
    /* 每页显示几条 */
    handleCurrentChange(val) {
      this.searchCondition.current = val;
      this.getResourceInfo();
    },

    /* 显示第几页 */
    handleSizeChange(val) {
      this.searchCondition.size = val;
      this.getResourceInfo();
    },

    /* 请求：获取表格中数据 */
    getResourceInfo() {
      this.disabledbtn = true;
      this.loading = true;
      this.Request.getResourceInfo(this.searchCondition)
        .then((res) => {
          this.disabledbtn = false;
          this.loading = false;
          if (res.status === 1) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loading = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 请求获取单个资源信息 */
    getResourceInfoByIdInfo(id) {
      this.Request.getResourceInfoByIdInfo({ id: id })
        .then((res) => {
          if (res.status === 1) {
            let data = res.data;
            this.resourceForm.id = data.id;
            this.resourceForm.type = data.type;
            this.resourceForm.code = data.code;
            this.resourceForm.name = data.name;
            this.resourceForm.url = data.url;
            this.resourceForm.description = data.description;
            this.resourceForm.method = data.method;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 获取公共的类型信息 */
    getCommonTypeInfo(data, objArray) {
      this.Request.getPropList({ propTypeCode: data })
        .then((res) => {
          if (res.status === 0) {
            objArray.forEach((item) => {
              this[item] = res.data;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 获取获取字典数据详细信息 */
    getDictDataInfo(data, objArray) {
      this.Request.getDictDataInfo({ dictType: data })
        .then((res) => {
          if (res.status === 1) {
            objArray.forEach((item) => {
              this[item] = res.data;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 双击当前行 */
    rowDblclick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },

    /* 点击编辑按钮 */
    handleViewEdit(index, row, code, name) {
      if ('view' === code) {
        this.dialogTitle = name;
        this.isDisabledbtn = true;
        this.closeOnClickModal = true;
      } else if ('edit' === code) {
        this.dialogTitle = name;
        this.methodType = 'PUT';
      }
      this.getResourceInfoByIdInfo(row.id);

      this.showType = code;

      this.editVisible = true;
    },

    /* 点击删除按钮 */
    handleDelete(index, row) {
      this.id = row.id;
      this.delVisibleType = 'delete';
    },

    /* 搜索 */
    searchInfo() {
      /* 重置到第一页 */
      this.searchCondition.current = 1;
      this.searchCondition.size = 10;
      this.getResourceInfo();
    },

    /* 重置搜索内容 */
    resetSearch() {
      this.searchCondition.name = '';
      this.searchCondition.url = '';
      this.searchCondition.method = '';
      this.searchCondition.type = '';
      this.searchInfo();
    },

    /* 新增 */
    addData() {
      this.dialogTitle = '新增';
      this.editVisible = true;
    },

    /* 批量删除 */
    batchDelete(method) {
      /* 获取选中的数据 */
      let selection = this.$refs.multipleTable.store.states.selection;
      this.selectTableData = selection;
      if (selection.length > 0) {
        this.delVisibleType = 'batchDelete';
        this.deleteRow(method);
      } else {
        this.$message.warning('请至少选择一条数据');
      }
    },

    /* 关闭新增编辑查看 弹出框事件 */
    closedFormDialog() {
      /* 初始化数据使用clearValidate清空校验，
        resetFields方法在点击编辑而后点击新增时是无效的，
        所以还是要手动初始化所有的值
      */
      this.isDisabledbtn = false;
      this.resourceForm.id = '';
      this.resourceForm.code = '';
      this.resourceForm.description = '';
      this.resourceForm.method = '';
      this.resourceForm.name = '';
      this.resourceForm.type = '';
      this.resourceForm.url = '';

      this.closeOnClickModal = false;
      this.showType = 'add';
      this.methodType = 'POST';
      this.$refs['resourceForm'].clearValidate();
    },

    /* 保存或编辑 */
    submitForm(formName, formData, type, method, refreshMethod) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitFormInfo(formData, type, method, refreshMethod);
        } else {
          /* 提示还有需要填写的信息 */
          this.$message.warning('请填写所有必填信息');
          return false;
        }
      });
    },

    /* 保存或编辑信息 */
    submitFormInfo(formData, type, method, refreshMethod) {
      /* 防止多次提交 */
      this.disabledbtn = true;
      this.loadingDialog = true;
      this.Request[method](formData, type)
        .then((res) => {
          this.disabledbtn = false;
          this.loadingDialog = false;
          if (res.status === 1) {
            this.editVisible = false;
            this.$message.success(res.msg);
            /* 重新刷新数据 */
            this[refreshMethod]();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loadingDialog = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 保存或编辑 取消提交 */
    cancelSubmit(formName) {
      /* bug原因，不用api提供的方法 不信你试试 */
      // this.$refs[formName].resetFields();
      this.editVisible = false;
    },

    /* 打开删除弹框 */
    deleteMessageBox(method) {
      this.$confirm('删除不可恢复，是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteRow(method);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    /* 确定删除 */
    deleteRow(method) {
      if (
        this.delVisibleType !== 'delete' &&
        this.delVisibleType !== 'batchDelete'
      ) {
        this.$message.error(`别偷偷的修改特定的参数哦`);
        return;
      }
      let selection = [];
      let length = 0;
      /* 获取要删除数据的id值数组 (单个与批量删除相同) */
      let idArray = [];
      if (this.delVisibleType === 'delete') {
        idArray.push(this.id);
      } else if (this.delVisibleType === 'batchDelete') {
        /*获取选中的值 */
        selection = this.$refs.multipleTable.store.states.selection;
        length = selection.length;
        for (let i = 0; i < length; i++) {
          idArray.push(selection[i].id);
        }
      }
      /* 删除一条或多条数据 */
      this.deleteInfo({ idArray: idArray }, method);
    },

    /* 删除后的信息 */
    deleteInfo(data, method) {
      this.disabledbtn = true;
      this.loading = true;
      this.Request[method](data)
        .then((res) => {
          this.disabledbtn = false;
          this.loading = false;
          if (res.status === 1) {
            /* 当删除成功后，删除对应选中的数据或单个数据 */
            for (let j = this.tableData.length - 1; j >= 0; j--) {
              for (let i = 0; i < data.idArray.length; i++) {
                if (data.idArray[i] === this.tableData[j].id) {
                  this.tableData.splice(j, 1);
                  break;
                }
              }
            }
            this.$message.success(`成功删除了${data.idArray.length}条数据`);
            this.selectTableData = []; /* 清除选中的数据 */
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loading = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    }
  }
};
</script>

<style scoped>
/* layout-布局 */
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
